﻿#include "ed_aes.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "aes.h"
#include "aes_params.h"


#define AES_BLK_SIZE     16

#define DEFAULT_AES_KEY  "c2mujs64hr8ywbfk"

//#define DEFAULT_AES_KEY  "mu7y3shg8f4hz6kj"

static char  s_aes_key[17] = { 0 };


void set_aes_key(char* key)
{
	if (strlen(key) == 16)
	{
		memcpy(s_aes_key, key, 16);
	}
}

unsigned int calc_file_sum(unsigned char* data, int len)
{
	unsigned int sum = 0;
	int i;
	for (i = 0; i < len; ++i)
	{
		sum += data[i];
	}
	return sum;
}

unsigned char aes_encrypt(unsigned char* in_buf, int in_len,unsigned char* out_buf, int* out_len)
{
	int nRound = AES_ROUND;
	unsigned char pt[17] = { 0 };
	unsigned char key[17] = { 0 };
	unsigned char expansionkey[15 * 16] = { 0 };
	int count = in_len / AES_BLK_SIZE;
	int rest = in_len % AES_BLK_SIZE;
	int i = 0;
	int idx = 0;

	if (NULL == in_buf || NULL == out_buf || NULL == out_len)
	{
		return false;
	}
	if (in_len < AES_MIN_LEN)
	{
		return false;
	}
	if (strlen(s_aes_key) != 16)
	{
		memcpy(s_aes_key, DEFAULT_AES_KEY, 16);
	}

	if (rest > 0)
	{
		count += 1;
	}
	*out_len = 0;

	memcpy(key, s_aes_key, strlen(s_aes_key));
	ScheduleKey(key, expansionkey, 4, nRound);	// 1、密钥扩展生成

	for (i = 0; i < count; ++i)
	{
		idx = i * AES_BLK_SIZE;
		memset(pt, 0, sizeof(pt));
		memcpy(pt, in_buf + idx, AES_BLK_SIZE);
		AesEncrypt(pt, expansionkey, nRound);   // 2、AES 加密
		memcpy(out_buf + idx, pt, AES_BLK_SIZE);

		*out_len += AES_BLK_SIZE;
	}

	//printf("after  : ");

	//for (i = 0; i < *after_len; i++)
	//{
	//	printf("%02X ", after_buf[i]);
	//}
	//printf("\n");

	return true;
}

unsigned char aes_decrypt(unsigned char* in_buf, int in_len,unsigned char* out_buf, int* out_len)
{
	int nRound = AES_ROUND;
	unsigned char pt[17] = { 0 };
	unsigned char key[17] = { 0 };
	unsigned char expansionkey[15 * 16] = { 0 };
	int count = in_len / AES_BLK_SIZE;
	int rest = in_len % AES_BLK_SIZE;
	int idx = 0;
	int i = 0;

	if (NULL == in_buf || NULL == out_buf || NULL == out_len)
	{
		return false;
	}
	if (in_len < AES_BLK_SIZE || rest != 0)
	{
		return false;
	}
	if (strlen(s_aes_key) != 16)
	{
		memcpy(s_aes_key, DEFAULT_AES_KEY, 16);
	}

	*out_len = 0;
	memcpy(key, s_aes_key, strlen(s_aes_key));

	ScheduleKey(key, expansionkey, 4, nRound);	//1、密钥扩展生成

	for (i = 0; i < count; ++i)
    {
        idx = i * AES_BLK_SIZE;
        memset(pt, 0, sizeof(pt));
        memcpy(pt, in_buf + idx, AES_BLK_SIZE);
        Contrary_AesEncrypt(pt, expansionkey, nRound);//AES 解密
        memcpy(out_buf + idx, pt, AES_BLK_SIZE);

        *out_len += AES_BLK_SIZE;
	}

	return true;
}

